package com.jinbooks.web.login.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import com.jinbooks.authn.SignedPrincipal;
import com.jinbooks.authn.dto.LoginUser;
import com.jinbooks.authn.jwt.AuthJwt;
import com.jinbooks.authn.jwt.service.AuthRefreshTokenService;
import com.jinbooks.persistence.service.LoginService;
import com.jinbooks.web.login.service.IAuthStrategy;
import com.jinbooks.web.login.service.SysLoginService;
import com.jinbooks.web.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("normal" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class NormalAuthStrategy implements IAuthStrategy {

    @Autowired
    SysLoginService sysLoginService;
    @Autowired
    private AuthRefreshTokenService refreshTokenService;

    @Override
    public AuthJwt login(Authentication authentication) {
        if (authentication == null) {
            return null;
        }
        String refreshToken = refreshTokenService.genRefreshToken(authentication);

        SignedPrincipal principal = ((SignedPrincipal) authentication.getPrincipal());

        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = sysLoginService.buildLoginUser(principal.getUserInfo());

        SaLoginParameter model = new SaLoginParameter();
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        // 生成token
        LoginHelper.login(loginUser, model);

        return new AuthJwt(
                StpUtil.getTokenValue(),
                authentication,
                StpUtil.getTokenTimeout(),
                refreshToken);
    }

}
